//
//  HomeViewController.m
//  MZJ
//
//  Created by XDD on 16/6/3.
//  Copyright © 2016年 XDD. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeView.h"
#import "PersonDataVC.h"
#import "RescueViewController.h"
#import "InformationVC.h"
#import "VolunteersVC.h"
#import "CareViewController.h"
#import "QueryViewController.h"
#import "PublicViewController.h"
#import "HelpViewController.h"
#import "CareDetailVC.h"
#import "News_DetailViewController.h"

@interface HomeViewController () <ModelDelegate,UIScrollViewDelegate> {
    NSString *unickname_Str;
    //图片轮播
    NSTimer *timer_;
    BOOL isFromStart_;
    
}

@property (nonatomic, strong) HomeView *homeView;
@property (nonatomic, strong) ModelViewController *modelViewController;
@property (nonatomic, strong) NetWorkingSModel *model;
@property (nonatomic, strong) UIScrollView *carousel_ScrollView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSArray *home_img_arr;

@end

@implementation HomeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    [self person_data_httprequest];

//    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.homeView.hidden = NO;
    
    _carousel_ScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 0.31*kHeight)];
    _carousel_ScrollView.backgroundColor = [UIColor colorWithRed:253/255.0 green:179/255.0 blue:10/255.0 alpha:1];
    _carousel_ScrollView.delegate = self;
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(kWidth/2 - 30, _carousel_ScrollView.frame.size.height/2 - 35, 60, 70)];
    imageView.image = [UIImage imageNamed:@"xingzhaung_NONet"];
    [_carousel_ScrollView addSubview:imageView];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, _carousel_ScrollView.frame.size.height/2 + 55, kWidth - 20, 15)];
    label.text = @"亲~您的网络不给力喔!";
    label.font = [UIFont systemFontOfSize:13];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    [_carousel_ScrollView addSubview:label];
    
    _carousel_ScrollView.showsHorizontalScrollIndicator = NO;
    [_carousel_ScrollView setPagingEnabled:YES];  //视图整页显示
    [self.view addSubview:_carousel_ScrollView];
    
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 0.31*kHeight)];

//    view.backgroundColor = [UIColor blackColor];
//    [_carousel_ScrollView addSubview:view];
    [self addTimer];
    
    // 页面指示器
    CGRect frame = self.view.frame;
//    frame.origin.x =  kWidth - 100;
//    frame.origin.y = _carousel_ScrollView.frame.origin.y + 0.31*kHeight - 20;
    frame.origin.x = (frame.size.width - kWidth) / 2;
    frame.origin.y = _carousel_ScrollView.frame.origin.y + 0.31*kHeight - 20;
    frame.size.width = kWidth;
    frame.size.height = 20;
    _pageControl = [[UIPageControl alloc] initWithFrame:frame];
    _pageControl.hidesForSinglePage = YES;
    _pageControl.userInteractionEnabled = YES;
    _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    _pageControl.currentPage = 0;
    
    [_pageControl addTarget:self action:@selector(pageControlValueChangedAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_pageControl];

    
    [XJNetWorkingManager successHandler:^(id responseObject) {
    
        NSLog(@"%@",responseObject);
        
        if ([responseObject[@"statu"] intValue] == 0) {
            _home_img_arr = responseObject[@"result"];
            _pageControl.numberOfPages = _home_img_arr.count;
            [_carousel_ScrollView setContentSize:CGSizeMake(kWidth*_home_img_arr.count, 0)];
            for (int i = 0; i < _home_img_arr.count; i++) {
                
                UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(kWidth*i, 0, kWidth, 0.31*kHeight)];
                imageview.userInteractionEnabled = NO;
                [imageview sd_setImageWithURL:[NSURL URLWithString:_home_img_arr[i][@"tiimg"]]
                             placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
                [_carousel_ScrollView setCanCancelContentTouches:YES];
                [imageview setUserInteractionEnabled:YES];
//                NSLog(@"%@",[DataModel object].home_img_Arr[i][@"tiimg"]);
                [_carousel_ScrollView addSubview:imageview];
                
                UITapGestureRecognizer *tap  = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(magnifyImage)];
                
                [imageview addGestureRecognizer:tap];
                
            }

        }
        
//        NSLog(@"轮播 = %@",responseObject);
    } failureHandler:^(NSError *error) {
        
    }];

}

- (void)magnifyImage {

    NSInteger page = _pageControl.currentPage;
    for (int j = 0; j < _home_img_arr.count; j++) {
        if (page == j) {
            
            if ([_home_img_arr[j][@"tiurl"] rangeOfString:act_info_News].location != NSNotFound) {
                NSRange range2 = [_home_img_arr[j][@"tiurl"] rangeOfString:@"acid"];
                NSString *str2 = [_home_img_arr[j][@"tiurl"] substringFromIndex:range2.location];
                [DataModel object].care_ID_Str =  [str2 substringFromIndex:5];
                CareDetailVC *careDetailVC = [[CareDetailVC alloc]init];
                [self.navigationController pushViewController:careDetailVC animated:YES];
            }
            if ([_home_img_arr[j][@"tiurl"] rangeOfString:station_news_Detail].location != NSNotFound) {
                NSRange range2 = [_home_img_arr[j][@"tiurl"] rangeOfString:@"arid"];
                NSString *str2 = [_home_img_arr[j][@"tiurl"] substringFromIndex:range2.location];
                [DataModel object].news_arid_Str =  [str2 substringFromIndex:5];
                News_DetailViewController *news_DetailViewController = [[News_DetailViewController alloc]init];
                [self.navigationController pushViewController:news_DetailViewController animated:YES];
            }
        }
    }

//    for (j = 0; j < i; j++) {
//    }
//    UIImageView * imageView = imageview;
//    NSLog(@"%@",_home_img_arr[j][@"tiimg"]);
    
}

- (void)person_data_httprequest {
    if (!_model) {
        _model = [[NetWorkingSModel alloc] init];
    }
    __weak typeof (self)weakSelf = self;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *token = [user objectForKey:@"user_token"];
    if (token.length != 0) {
        
        [dic setObject:token forKey:@"token"];
    }
    [_model setBlockWithReturnBlock:^(id returnValue) {

        [weakSelf.modelViewController userInfo_data_save:@"useDetail.txt" responseObject:returnValue[@"result"]];
        [DataModel object].userDetail = returnValue[@"result"];
//        NSLog(@"个人信息下载 = %@",returnValue);
    } WithErrorBlock:^(id errorCode) {
        NSLog(@"%@",errorCode);
        if ([[NSString stringWithFormat:@"%@",errorCode] isEqualToString:@"网络连接失败！"]) {
            [DataModel object].statu_Str = @"1";
        } else {
            [DataModel object].statu_Str = errorCode[@"statu"];
        }
        
    }];
    [weakSelf.model userGetUserinfo:dic];
}
- (void)addTimer{
    
    timer_ = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(scrollPages:) userInfo:nil repeats:YES];

}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //    关闭定时器(注意点; 定时器一旦被关闭,无法再开启)
        [timer_ invalidate];
//    [timer_ removeTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    //    开启定时器
    [self addTimer];
}

- (IBAction)scrollPages:(id)sender {
    ++_pageControl.currentPage;
    CGFloat pageWidth = CGRectGetWidth(_carousel_ScrollView.frame);
    if (isFromStart_) {
        [_carousel_ScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        _pageControl.currentPage = 0;
    }
    else
    {
        [_carousel_ScrollView setContentOffset:CGPointMake(pageWidth*_pageControl.currentPage, _carousel_ScrollView.bounds.origin.y)];
        
    }
    if (_pageControl.currentPage == _pageControl.numberOfPages - 1) {
        isFromStart_ = YES;
    }
    else
    {
        isFromStart_ = NO;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    CGFloat pageWidth = sender.frame.size.width;
    int page = floor((sender.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    _pageControl.currentPage = page;
}

- (IBAction)pageControlValueChangedAction:(id)sender {
    UIPageControl *pageControl = sender;
    NSInteger currentPage = pageControl.currentPage;
    
    CGRect frame = _carousel_ScrollView.bounds;
    frame.origin.x = frame.size.width * currentPage;
    [_carousel_ScrollView scrollRectToVisible:frame animated:YES];
    
}

- (HomeView *)homeView {
    if (!_homeView) {
        _homeView = [[HomeView alloc]initWithFrame:self.view.bounds];
        [self.view addSubview:_homeView];

         __weak typeof (self)weakSelf = self;

        [_homeView setDidqueryBlock:^{
            QueryViewController *queryViewController = [[QueryViewController alloc]init];
            [weakSelf.navigationController pushViewController:queryViewController animated:YES];
        }];
        [_homeView setDidcareBlock:^{
            CareViewController *careViewController = [[CareViewController alloc]init];
            [weakSelf.navigationController pushViewController:careViewController animated:YES];
        }];
        [_homeView setDidvolunteersBlock:^{
            HelpViewController *helpViewController = [[HelpViewController alloc]init];
            [weakSelf.navigationController pushViewController:helpViewController animated:YES];
        }];
        [_homeView setDidinformationBlock:^{
            InformationVC *informationVC = [[InformationVC alloc]init];
            [weakSelf.navigationController pushViewController:informationVC animated:YES];
        }];
        [_homeView setDidrescueBlock:^{

            VolunteersVC *volunteersVC = [[VolunteersVC alloc]init];
            [weakSelf.navigationController pushViewController:volunteersVC animated:YES];
        }];
        [_homeView setDidhelpBtnBtnBlock:^{
            PublicViewController *publicViewController = [[PublicViewController alloc]init];
            [weakSelf.navigationController pushViewController:publicViewController animated:YES];
        }];
    }
    return _homeView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end





